package com.dongwu.manager.service.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dongwu.common.dao.DynamicSpecifications;
import com.dongwu.common.dao.SearchFilter;
import com.dongwu.common.service.impl.BaseServiceImpl;
import com.dongwu.common.utils.UserUtils;
import com.dongwu.manager.dao.AdvertisingDao;
import com.dongwu.manager.entity.Advertising;
import com.dongwu.manager.service.AdvertisingService;
import com.dongwu.security.service.IUserService;

@Service
public class AdvertisingServiceImpl extends BaseServiceImpl<Advertising, String> implements AdvertisingService {
	@Autowired
	private IUserService userService;
	
    @Autowired
    private AdvertisingDao advertisingDao;
    
    Class<Advertising> entityClass = null;

	@SuppressWarnings("unchecked")
	public AdvertisingServiceImpl() {
		Type t = getClass().getGenericSuperclass();
		if (t instanceof ParameterizedType) {
			Type[] p = ((ParameterizedType) t).getActualTypeArguments();
			entityClass = (Class<Advertising>) p[0];
		}
	}
	@Transactional
	public Advertising save(Advertising entity) {
		if (entity.getUser() == null) {
			entity.setUser(userService.findByLoginName(UserUtils.getUserLoginName()));
		}
		// 吧当前选择的模板的模板类型给到模板类型字段
		entity.setAppTemplateTypeId(entity.getAppTemplate().getTemplateType().getId());
		// 吧当前选择的模板的模板唯一编码给到模板唯一编码
		entity.setAppTemplateTypeSn(entity.getAppTemplate().getTemplateType().getTemplateTypeSn());
		return super.save(entity);
	}
	@Override
	public Long getCount(Map<String, Object> searchParams, String userId) {
		Long devList=null;
		if(userId == null){
			// TODO Auto-generated method stub
			Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
			Specification<Advertising> spec = DynamicSpecifications.bySearchFilter(filters.values(), entityClass);
			// 返回当前用户的所有投放记录
			devList = advertisingDao.count(spec);
		}else{
			devList = advertisingDao.countByUserid(userId);
		}
		return devList;
		
	}
	@Override
	public List<Advertising> getAdsForClassify(String deviceId, Integer status, String classifyId) {
		return advertisingDao.getAdsForClassify(deviceId, status, classifyId);
	}
}
